<!DOCTYPE html>
<html>
  <meta
    name="viewport"
    content="initial-scale=1.0, maximum-scale=1, minimum-scale=1, user-scalable=no,uc-fitscreen=yes"
  />
  <head>
    <style>
      body {
        margin: 0px;
        padding: 0px;
      }
      .min {
        width: 100%;
        display: flex;
        justify-content: center;
      }
      .minCent {
        width: 100%;
      }
      .function {
        margin: 10px;
      }
      .mr-T {
        margin-top: 5px;
      }
      .text {
        text-align: center;
        font-size: 16px;
      }
      .centerbox {
        padding: 20px;
      }
    </style>
  </head>
  <body>
    <!-- 第一张图片：<input type="file" name="file" id="change" > -->
    <!-- 图片：<input type="file" name="file2" id="change2" /> -->
    <!-- <a href="" id="download" download="测试图片.png">点我下载</a> -->
    <div class="min">
      <div class="centerbox">
        <div class="text">长按图片保存</div>
        <div class="minCent">
          <canvas id="myCanvas" width="300" height="300"></canvas>
        </div>
        <div class="function">
          <div class="mr-T">
            <input type="file" name="file2" id="change2" />
          </div>
          <div class="mr-T">
            <button class="button" onclick="button()">重新上传</button>
          </div>
        </div>
      </div>
    </div>

    <script>
      var canvas = document.getElementById('myCanvas')
      var context = canvas.getContext('2d')
      var img1 = new Image()
      img1.src = '1.png'
      img1.onload = imgfn //图片加载完在执行
      function imgfn() {
        var bg = context.createPattern(img, 'no-repeat') //createPattern() 方法在指定的方向内重复指定的元素。
        context.fillStyle = bg
        context.fillRect(0, 0, context.width, context.height) //绘制已填充矩形fillRect(左上角x坐标, 左上角y坐标, 宽, 高)
      }
      var btn = document.getElementById('btn')
      var change2 = document.getElementById('change2')
      var img2 = new Image()
      //处理跨域
      img2.crossOrigin = 'anonymous'
      change2.onchange = function (event) {
        var file = event.target.files[0]
        var url = window.URL.createObjectURL(file)
        img2.src = url
      }
      img2.onload = function () {
        context.drawImage(img2, 0, 0, 300, 300)
      }
      img1.onload = function () {
        context.globalCompositeOperation = 'destination-over'
        context.drawImage(img1, 0, 0, 300, 300)
      }
      function button() {
        window.location.reload()
      }
    </script>
  </body>
</html>
